package com.cems.controller;

import com.cems.mapper.EntrustMapper;
import com.cems.pojo.SysAdmin;
import com.cems.pojo.SysEntrust;
import com.cems.pojo.SysUser;
import com.cems.pojo.*;
import com.cems.service.AdminService;
import com.cems.service.EntrustService;
import com.cems.service.UserService;
import com.cems.util.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName loginController
 * @Author 陈新予(blank)
 * @Date 2021/5/16
 * @Version 1.0
 */
@Controller
public class loginController {
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;
    @Autowired
    EntrustService entrustService;
    @Autowired
    EntrustMapper entrustMapper;

    @GetMapping({"", "welcome"})
    public String Welcome(HttpSession session,HttpServletRequest req, Model model) {
        try{
            Boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
            if(isAdmin){
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
            }
        }catch (Exception e){
            System.err.println("小问题");
        }
        session = req.getSession();
        List<SysEntrust> entrusts = entrustService.getLeisureEntrusts();
        int pages;
        if (entrusts.size() % 5 == 0) {
            pages = entrusts.size() / 5;
        } else {
            pages = entrusts.size() / 5 + 1;
        }
        ArrayList<String> entrustTypeList = new ArrayList<>();
        ArrayList<String> entrustDataList = new ArrayList<>();
        ArrayList<String> entrustUserList = new ArrayList<>();
        ArrayList<String> entrustIdList = new ArrayList<>();
        ArrayList<String> entrustStartTime = new ArrayList<>();
        ArrayList<String> entrustEndTime = new ArrayList<>();
        ArrayList<String> entrustMoney = new ArrayList<>();
        for (SysEntrust entrust : entrusts) {
            if (entrustDataList.size() >= 9) {
                break;
            }
            if (entrust.getGmtEnd().after(new Date())) {
                entrustIdList.add(String.valueOf(entrust.getEntrustId()));
                entrustTypeList.add(entrustMapper.getEntrustTypeById(Integer.parseInt(entrust.getEntType())));
                entrustDataList.add(entrust.getEntData());
                entrustUserList.add(entrustMapper.getEntrustUserById(entrust.getEntConsignor()));
                entrustStartTime.add(new DateUtil().dateToString(entrust.getGmtCreate()));
                entrustEndTime.add(new DateUtil().dateToString(entrust.getGmtEnd()));
                entrustMoney.add(String.valueOf(entrust.getEntMoney()));
            }
        }
        session.setAttribute("limitentrustIdList", entrustIdList);
        session.setAttribute("limitentrustMoney", entrustMoney);
        session.setAttribute("limitentrustTypeList", entrustTypeList);
        session.setAttribute("limitentrustDataList", entrustDataList);
        session.setAttribute("limitentrustUserList", entrustUserList);
        session.setAttribute("limitentrustStartTime", entrustStartTime);
        session.setAttribute("limitentrustEndTime", entrustEndTime);
        session.setAttribute("limitLeisureEntrustspages", pages);
        return "index";
    }

    @GetMapping("toadminlogin")
    public String toadminlogin() {
        return "back/adminLogin";
    }

    @PostMapping("adminLogin")
    public String AdminLogin(String adminNum, String adminPwd, Model model) {
        Subject subject = SecurityUtils.getSubject();//获取用户信息
        UsernamePasswordToken token = new UsernamePasswordToken(adminNum, adminPwd);//封装
        try {
            subject.login(token);
            //通过subject取
            Session session = subject.getSession();
            Boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
            if (isAdmin) {
                SysAdmin admin = (SysAdmin) session.getAttribute("loginAdmin");
                model.addAttribute("adminName", admin.getAdminNum());
                SysAdmin sysAdmin = adminService.selOneSysAdmin(admin.getAdminNum());
                SysEcharts sys = userService.selOneSysSuc(sysAdmin.getId());
                Map<String,Object> map = new HashMap<>();
                map.put("adminId",sysAdmin.getId());
                map.put("loginNum",sys.getLoginNum()+1);
                userService.setSysLoginGraph(map);
                return "back/adminHome";
            } else {
                subject.logout();
                model.addAttribute("msg", "系统发生未知错误!");
                return "back/adminLogin";
            }
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", "没有用户名为:" + token.getPrincipal());
            return "back/adminLogin";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "账号或密码错误!");
            return "back/adminLogin";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg", "用户名 : " + token.getPrincipal() + ",被锁定了.请联系您的管理员解锁.");
            return "back/adminLogin";
        } catch (Exception e) {
            model.addAttribute("msg", "系统发生未知错误!");
            return "back/adminLogin";
        }
    }

    @GetMapping("logOut")
    public String logOut(HttpServletRequest req) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        HttpSession session = req.getSession();
        session.invalidate();
        return "back/adminLogin";
    }

    @GetMapping("userlogOut")
    public String userlogOut(HttpServletRequest req) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        HttpSession session = req.getSession();
        session.invalidate();
        return "User/userlogin";
    }

    /**
     * 用户登录
     */
    @GetMapping("toUserLogin")
    public String userToLogin() {
        return "User/userlogin";
    }
    @RequestMapping("userLogin")
    public String userLogin(String userNum, String userPwd, Model model) {
        Subject subject = SecurityUtils.getSubject();//获取用户信息
        UsernamePasswordToken token = new UsernamePasswordToken(userNum, userPwd);//封装
        try {
            subject.login(token);
            //通过subject取
            Session session = subject.getSession();
            Boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
            if (!isAdmin) {
                SysUser sysUser = (SysUser) session.getAttribute("user");
                model.addAttribute(" SysUser", sysUser);
                return "index";
            } else {
                subject.logout();
                model.addAttribute("msg", "系统发生未知错误!");
                return "User/userlogin";
            }
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", "");
            return "User/userlogin";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "账号或密码错误!");
            return "User/userlogin";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg", "用户名 : " + token.getPrincipal() + ",被锁定了.请联系您的管理员解锁.");
            return "User/userlogin";
        } catch (Exception e) {
            model.addAttribute("msg", "系统发生未知错误!");
            return "User/userlogin";
        }
    }
}
